Spring Inversion Of Control (IOC)


 

Spring Inversion Of Control (IOC)

In this tutorial you will learn about the Inversion Cf Control

In this tutorial you will learn about the Inversion Cf Control

Spring Inversion Of Control (IOC)

The Spring framework provides a powerful container that manages the components. This container is based on the Inversion Of Control and it is implemented by Dependency Injection design pattern. The container is responsible for choosing the resources here.

An example of IOC is given below please consider the example

Create an Interface

Employee.java

package net.roseindia;

public interface Employee {
	public String showDetail();
}

then create a class that implements this interface

PartimeEmployee.java

package net.roseindia;

public class PartimeEmployee implements Employee {
	@Override
	public String showDetail() {
		return "I Am A Part Time Employee";
	}
}

After this create another class that implements this Interface and perform some other job

FulltimeEmployee.java

package net.roseindia;

public class FulltimeEmployee implements Employee {
	@Override
	public String showDetail() {
		return "I Am Full Time Employee";
	}
}

Then create a service class as

EmployeeService.java

package net.roseindia;

public class EmployeeService {
	Employee employee;

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public String printDetail() {
		return employee.showDetail();
	}
}

Then map the above classes into xml file known as bean.xml as

bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="fulltimeEmployee" class="net.roseindia.FulltimeEmployee"></bean>
<bean id="partimeEmployee" class="net.roseindia.PartimeEmployee"></bean>
<bean id="employeeService" class="net.roseindia.EmployeeService">
<property name="employee">
<ref local="partimeEmployee"/>
</property>
</bean> 

</beans>


finally call this include this bean.xml file into your application as

MainClaz.java

package net.roseindia;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class MainClaz {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"beans.xml");
		EmployeeService employeeService = (EmployeeService) context.getBean("employeeService");
		System.out.println(employeeService.printDetail());
	}
}


When you run this application it will display message as shown below:


Am A Part Time Employee

Download Select Source Code

Ads